package e1

import (
	`fmt`
	`os`
	`reflect`

	`github.com/tealeg/xlsx/v3`
)

func InitExcel(filename string, sheetName string) (*xlsx.File, error) {
	wb, err := openOrCreateExcel(filename)
	if err != nil {
		return nil, err
	}

	sh, err := getOrCreateSheet(wb, sheetName)
	if err != nil {
		return nil, err
	}

	if sh.MaxRow == 0 {
		setTitleRow(sh)
	} else if firstRow, _ := sh.Row(0); !isMyTitleRow(firstRow) {
		return nil, fmt.Errorf("the first row not excepted row")
	}
	return wb, wb.Save(filename)
}

func openOrCreateExcel(filename string) (*xlsx.File, error) {
	if _, err := os.Lstat(filename); os.IsNotExist(err) {
		return xlsx.NewFile(), nil
	}
	if wb, err := xlsx.OpenFile(filename); err != nil {
		return nil, err
	} else {
		return wb, nil
	}
}

func getOrCreateSheet(wb *xlsx.File, sheetName string) (*xlsx.Sheet, error) {
	sh, ok := wb.Sheet[sheetName]
	if ok {
		return sh, nil
	}

	if sh, err := wb.AddSheet(sheetName); err == nil {
		return sh, nil
	} else {
		return nil, err
	}
}

func setTitleRow(sh *xlsx.Sheet) {
	row := sh.AddRow()
	for _, title := range TitleRow {
		cell := row.AddCell()
		cell.SetString(title)
		cell.Hidden = false
	}
}

func isMyTitleRow(row *xlsx.Row) bool {
	for i, title := range TitleRow {
		if row.GetCell(i).Value != title {
			return false
		}
	}
	return true
}

func SetRows(sh *xlsx.Sheet, dataLine []*ExperimentData) {
	for i := range dataLine {
		row := sh.AddRow()
		SetRow(row, dataLine[i])
	}
}

func SetRow(row *xlsx.Row, data *ExperimentData) {
	e := reflect.ValueOf(data).Elem()
	for i := 0; i < e.NumField(); i++ {
		row.AddCell().SetInt64(e.Field(i).Int())
	}
}
